package com.bbcare.mqservice.utils.rockermq;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Title		MqttProducerService.java
 * @Package		com.bbcare.mqservice.utils.rockermq
 * @Description	mqtt消息生产业务类
 * @Author		<a href="mailto:jiangqian_java@163.com">jiang</a>
 * @Date		2023/5/6
 * @Version		V1.0 
 * @Copyright	(c) Shanghai BBcare Medical Equipment Co.,Ltd.
 */
@Service
public class MqttProducerService {

    @Value("${mqtt.broker}")
    private String HOST;

    @Value("${mqtt.receiveTopic}")
    private String TOPIC;

    @Value("${mqtt.deviceId}")
    private String clientid;

    private MqttClient client;

    private MqttTopic topic11;

    private MqttMessage message;

    /**
     * 用来连接服务器
     */
    private void connect() throws MqttException {
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);

        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new PushCallback());
            client.connect(options);

            topic11 = client.getTopic(TOPIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param requestBody
     * @throws MqttPersistenceException
     * @throws MqttException
     */
    public boolean publish(String requestBody) throws MqttPersistenceException, MqttException {
        if(topic11 == null) {
            connect();
        }
        boolean flag;
        this.message = new MqttMessage();
        this.message.setQos(2);
        this.message.setRetained(true);
        this.message.setPayload(requestBody.getBytes());
        MqttDeliveryToken token = this.topic11.publish(message);
        token.waitForCompletion();
        System.out.println("message is published completely! " + token.isComplete());
        flag = token.isComplete();
        return flag;
    }

    /**
     * 启动入口
     *
     * @param args
     * @throws MqttException
     */
    public static void main(String[] args) throws MqttException {
        MqttProducerService server = new MqttProducerService();
        server.publish("发送消息");
        System.out.println(server.message.isRetained() + "------ratained状态");
    }


}
